package handler;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

/**
 * Connects, disconnects, and handles execution statements with the Database.  The
 * Database connection parameters are defined in the db.properties file.
 * 
 * Note: This connection gets it's database access properties through the
 *       db.properties file.  Any changes to the connection such as DatabaseURL,
 *       Database Password, DatabaseUsername, or Database should be changed
 *       there.
 * 
 * @author David Hietpas
 */
public class DBConnector {

	protected Connection connection;
	
	/**
	 * Connects to the Database from the criteria set in the db.properties file. 
	 * Opens a Database Connection.
	 * 
	 */
	public void connect()
	{
        Properties props = new Properties();
		try {
			FileInputStream is = new FileInputStream("db.properties");
			props.load(is);        
			String url = "jdbc:" + props.getProperty("database");
			String db = props.getProperty("dbuser");
			String pw = props.getProperty("dbpass");
			
			Class.forName("com.mysql.jdbc.Driver");
			connection = DriverManager.getConnection(url,db,pw);
			
			if(is != null)
				is.close();

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		
	}	
	
	
	/**
	 * Disconnects from the Database. Closes connection.
	 * 
	 */
	public void disconnect() {
		try {
			connection.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	
	
	/**
	 * Generic Execution Handler.  Handles CRUD statements.  Values are determined by casting
	 * the object type dynamically during execution. Insert will not return a ResultSet.
	 * 
	 * @param query string representing a mysql query statement.
	 * @param vals an object array of parameters for the query statement.
	 * @return set of results from the mysql query or null if no set was retrieved.
	 */
	protected ResultSet execute(String query, Object[] vals) {
		
		try{
			connection.setAutoCommit(false);
			PreparedStatement ps = connection.prepareStatement(query);
			
			for(int i = 0; i < vals.length; i++)
				ps.setObject(i+1, vals[i].getClass().cast(vals[i]));
			
			ps.execute();
			connection.commit();
			
			return ps.getResultSet();
			
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
	
	
	
	
	
}
